package com.distribute.core.netty;

import cn.hutool.core.lang.Assert;
import com.distribute.core.init.CacheReportClient;
import com.distribute.core.netty.handler.CacheClientHandler;
import com.distribute.core.netty.handler.CacheMemoryInfoHandler;
import com.distribute.core.netty.handler.MemoryStaticsHandler;
import com.distribute.core.netty.handler.ReconnectHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 本地缓存netty客户端 初始化
 *
 * @author chennengcheng
 * @date 2021-09-13 11:37
 * @remark
 */
public class LocalCacheClientInitializer extends ChannelInitializer<SocketChannel>{

	private static final Logger log = LoggerFactory.getLogger(LocalCacheClientInitializer.class);

	private ReconnectHandler reconnectHandler;

	private CacheClientHandler cacheClientHandler;

	private MemoryStaticsHandler memoryStaticsHandler;

	private CacheMemoryInfoHandler cacheMemoryInfoHandler;

    public LocalCacheClientInitializer(CacheReportClient tcpClient) {
		Assert.notNull(tcpClient, "TcpClient can not be null.");
		this.reconnectHandler = new ReconnectHandler(tcpClient);
		this.cacheClientHandler = new CacheClientHandler();
		this.memoryStaticsHandler = new MemoryStaticsHandler();
		this.cacheMemoryInfoHandler = new CacheMemoryInfoHandler();
	}

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();
		pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
		pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
		pipeline.addLast(this.cacheMemoryInfoHandler);
		pipeline.addLast(this.memoryStaticsHandler);
		pipeline.addLast(this.cacheClientHandler);
		pipeline.addLast(this.reconnectHandler);
		pipeline.addLast(new LengthFieldPrepender(4));
		pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));

	}
}